// termbox_utils.go
package termbox_utils

import (
	"fmt"

	"github.com/nsf/termbox-go"
)

// ClearScreen clears the termbox screen.
func ClearScreen() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
}

// // DrawMenu draws the menu with the given options and selected index.
func DrawMenu(options []string, selectedIndex int) {
	ClearScreen()
	for i, option := range options {
		for j, char := range option {
			if i == selectedIndex {
				if j == 0 {
					termbox.SetCell(j, i, '>', termbox.ColorDefault, termbox.ColorDefault)
				}
				termbox.SetCell(j+2, i, char, termbox.ColorDefault, termbox.ColorDefault)
			} else {
				termbox.SetCell(j, i, char, termbox.ColorDefault, termbox.ColorDefault)
			}
		}
	}
	termbox.Flush()
}

func Print(msg string) {
	DrawMenu([]string{msg}, 0)
}

func Printf(format string, arg ...any) {
	msg := fmt.Sprintf(format, arg...)
	Print(msg)
}

func Println(arg ...any) {
	msg := fmt.Sprintln(arg...)
	Print(msg)
}

// DisplayMenu displays a list of options and allows the user to navigate using arrow keys.
func DisplayMenu(options []string) (int, error) {
	selectedIndex := 0

	for {
		DrawMenu(options, selectedIndex)

		key := PollKeyboardEvent()
		switch key {
		case termbox.KeyArrowUp:
			{
				if selectedIndex > 0 {
					selectedIndex--
				}
			}
		case termbox.KeyArrowDown:
			{
				if selectedIndex < len(options)-1 {
					selectedIndex++
				}
			}
		case termbox.KeyEnter:
			{
				return selectedIndex, nil
			}
		case termbox.KeyEsc:
			{
				return selectedIndex, fmt.Errorf("press KeyCtrlC, exit")
			}
		}
	}
}

// InitTermbox initializes the termbox library.
func Init() {
	err := termbox.Init()
	if err != nil {
		msg := fmt.Sprintf("error initializing termbox: %v", err)
		panic(msg)
	}
}

// CloseTermbox closes the termbox library.
func CloseTermbox() {
	termbox.Close()
}

// PollKeyboardEvent waits for and returns a keyboard event.
func PollKeyboardEvent() termbox.Key {
	switch ev := termbox.PollEvent(); ev.Type {
	case termbox.EventKey:
		return ev.Key
	case termbox.EventError:
		return termbox.KeyEsc
	}
	return termbox.KeyEsc
}
